import moment from 'moment'
import axios  from 'axios'
import {
	apiConfig,
	gatewayUrl,
	usePermission
}             from '@/common/config'

const getRequiredRole    = (label) => ({required: true, message: `请输入${label}`, trigger: ['blur']})
export const requireRole = (item = {}) => ({...item, rules: item.required ? [getRequiredRole(item.label)] : undefined})

export const configMaker = config => {
	const {columns}   = config
	const form        = {}
	const formColumns = columns.filter(e => !e.notForm).map(e => {
		const rules = []
		e.required && rules.push(getRequiredRole(e.label))
		e.rules       = rules
		form[e.value] = ''
		return e
	})

	const searchColumns = []
	columns.forEach(col => {
		const hasIndex = searchColumns.findIndex(e => e.key == col.key)
		if (~hasIndex) {
			searchColumns.splice(hasIndex, 1)
		}
		searchColumns.push(col)
	})
	const tableColumns = []
	columns.forEach(col => {
		const hasIndex = tableColumns.findIndex(e => e.key == col.key)
		if (~hasIndex) {
			tableColumns.splice(hasIndex, 1)
		}
		tableColumns.push(col)
	})
	return {
		...config,
		tableColumns : tableColumns.filter(e => !e.notTable).sort((a, b) => a.order - b.order),
		searchColumns: searchColumns.filter(e => e.inSearch),
		formColumns,
		form,
	}
}

export const getDefaultRangeTime = (n = 1, type = 'hours', format = 'yyyy-MM-dd hh:mm:ss') => {
	const now      = moment().valueOf()
	const before   = moment().add(n, type).valueOf()
	const startStr = moment(before).format(format)
	const endStr   = moment(now).format(format)
	return {
		startTime   : before,
		endTime     : now,
		startStrTime: startStr,
		endStrTime  : endStr,
	}
}

export const toLogin = () => {
	window.location.href = usePermission ? apiConfig.unifiedLoginUrl : '/login'
}

export function goback() {
	window.location.replace('../');
}

export const getDimTableItem = ({key, dimTableList}) => {
	return dimTableList.find(item => item.key == key);
}

//在url上截取门户系统的 token 和 id  --胡贺峰
export const getUrlSearch = (name) => {
	// 未传参，返回空
	if (!name) return null;
	// 查询参数：先通过search取值，如果取不到就通过hash来取
	var after = window.location.search;
	after     = after.substr(1) || window.location.hash.split('?')[1];
	// 地址栏URL没有查询参数，返回空
	if (!after) return null;
	// 如果查询参数中没有"name"，返回空
	if (after.indexOf(name) === -1) return null;

	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
	// 当地址栏参数存在中文时，需要解码，不然会乱码
	var r   = decodeURI(after).match(reg);
	// 如果url中"name"没有值，返回空
	if (!r) return null;

	return r[2];
}
//获取用户信息
export const getUserInfo  = async ({token} = {}) => {
	if (!token) return;
	const res = await axios({
		url    : '/jwcloud/system/findCurrentUserDetail',
		method : 'get', // 默认是 get
		headers: {'access_token': token}, //'3523ff19-fe28-4f58-8663-a9480e07912c'
	})

	return res.data.data;
}
//获取Org, 发送ajax时, header要加上东西
export const getOrgInfo   = async ({token} = {}) => {
	if (!token) return;
	const res = await axios({
		url    : '/jwcloud/system/getOrg',
		method : 'get', // 默认是 get
		headers: {'access_token': token}, //'3523ff19-fe28-4f58-8663-a9480e07912c'
	});

	var temp = {len: 10000, org: ""};
	var list = res.data.data;
	for (let i = 0; i < list.length; i++) {
		if (!list[i].path) {
			temp.len = list[i].id.length;
			temp.org = list[i].id;
			continue;
		}
		if (list[i].path.length < temp.len) {
			temp.len = list[i].path.length;
			temp.org = list[i].id;
		}
	}

	return temp.org;
}
//获取门户权限菜单
export const getMenuData  = async ({token} = {}) => {
	if (!token) return;
	const {data: {code, data}} = await axios({
		url    : '/jwcloud/system/findResource',
		method : 'post', // 默认是 get
		headers: {'access_token': token}, //'3523ff19-fe28-4f58-8663-a9480e07912c'
	})

	if (code !== String(200)) {
		window.history.go(-1); //暂时这么写
		return;
	}
	return data;
}
